<?php


namespace App\Http\Controllers\Saas;


use App\Http\Controllers\Controller;
use App\Utils\Result;
use Illuminate\Http\Request;
use App\Service\OSS;
use Illuminate\Support\Str;

class UploadController extends Controller
{
//    public function upload(Request $request): \Illuminate\Http\JsonResponse
//    {
//        $file = $request->file('file');
//        if (!$file) {
//            return Result::error(400, '请选择上传的文件');
//        }
//        $fileContent = file_get_contents($file->getRealPath());
//        $fileKey = 'dianbiao/' . date('Ymd') . '/' . md5($fileContent) . '.' . strtolower($file->getClientOriginalExtension());
//        OSS::publicUploadContent(env('OSS_BUCKET', 'yimits'), $fileKey, $fileContent, [
//            'CacheControl' => 'max-age=604800',
//            'ContentType' => $file->getClientMimeType(),
//        ]);
//        //unlink($file->getRealPath());
//
//        return Result::success([
//            'url' => env('OSS_DOMAIN') . '/' . $fileKey
//        ]);
//    }

    public function upload(Request $request): \Illuminate\Http\JsonResponse
    {
        $file = $request->file('file');
        if (!$file) {
            return Result::error(400, '请选择上传的文件');
        }
        $filePath = 'storage/admin_' . date('Ymd') . '_' . Str::random(16);
        $newFileName = $file->getClientOriginalName();

        if (!file_exists(public_path($filePath))) {
            mkdir(public_path($filePath));
        }
        $file->move(public_path($filePath), $newFileName);

        return Result::success([
            'url' => env('APP_URL') . '/' . $filePath . '/' . $newFileName
        ]);
    }
}
